
var notes = new Array();
var note_index = 0;
var noteboard;
var notes_element;
var active_note;
var cposx;
var cposy;

//initiallize the noteboard
function init(){
    noteboard = document.getElementById("noteboard");
    notes_element = document.createElement("div");
    notes_element.id = "notes";
    noteboard.appendChild(notes_element);
    if(localStorage.notes){
        load_notes(JSON.parse(localStorage.notes));
    }
    noteboard.onmouseup = mouse_up;
    noteboard.onmouseout = mouse_up;
    noteboard.onmousedown = mouse_down;
    noteboard.onkeyup = key_up;
    noteboard.onclick = click;
    window.oncontextmenu = context_menu;
    window.onunload = unload;
    sort_notes();
    update_notes();
    setTimeout("post_noteboard_to_server()",3000);
}

//loads a new list of notes
function load_notes(l_notes){
    delete_all_notes();
    notes = l_notes;
    for(var i = 0; i < notes.length; i++){
        notes_element.appendChild(parse_note_to_html(notes[i]));
    }
    note_index = notes.length;
}

//removes one note from the list of notes and from the html
function delete_note(note){
    notes_element.removeChild(document.getElementById(note.id));
    notes.splice(notes.indexOf(note), 1);
    note_index = notes.length;
    sort_notes();
}

//removes all notes from the list of notes and from the html
function delete_all_notes(){
    for(var i = 0; i < notes.length; i++){
        notes_element.removeChild(document.getElementById(notes[i].id));
    }
    notes = new Array();
    note_index = notes.length;
}

//adds a new note to the list of notes
function new_note(x,y,h,w,c,t,a,v){
    //TODO - Unique Note ID, USERNAME|PASSWORDHASH|
    notes[note_index] = new Object();
    notes[note_index].id = Math.floor(Math.random()*101);
    notes[note_index].x_pos = x;
    notes[note_index].y_pos = y;
    notes[note_index].height = h;
    notes[note_index].width = w;
    notes[note_index].color = c;
    notes[note_index].text = t;
    notes[note_index].time = new Date().getTime();
    notes[note_index].zIndex = 10;
    if(a){
        notes[note_index].audio = a;
    }
    if(v){
        notes[note_index].video = v;
    }
    return notes[note_index++];
}

//sorts the notes according to last time used
function sort_notes()
{
    notes.sort(compare_notes);
}

//compare notes according to last time used
function compare_notes(n_a,n_b)
{
    return n_a.time - n_b.time;
}

//update all the notes
function update_notes(){
    for(var i = 0; i < notes.length; i++){
        notes[i].zIndex = i;
        update_note_style(notes[i]);
    }
}

//updates the position, color, and size of note
function update_note_style(note){
    var note_html = document.getElementById(note.id);
    note_html.style.top = note.y_pos + "px";
    note_html.style.left = note.x_pos + "px";
    note_html.style.height = note.height + "px";
    note_html.style.width = note.width + "px";
    note_html.style.zIndex = note.zIndex;
    var textArea = note_html.getElementsByTagName("textarea")[0];
    textArea.style.backgroundColor = note.color;
}

//return the html of note
function parse_note_to_html(note){
    var html = document.createElement("div");
    html.id = note.id;
    html.className = "note";
    html.style.top = note.y_pos + "px";
    html.style.left = note.x_pos + "px";
    html.style.height = note.height + "px";
    html.style.width = note.width + "px";
    html.style.zIndex = note.zIndex;
    var textArea = document.createElement("textarea");
    textArea.onchange = text_area_change;
    textArea.value = note.text;
    textArea.style.backgroundColor = note.color;
    textArea.id = 'ta' + note.id;
    textArea.placeholder = "I just thought...";
    $("#" + textArea.id).resizable();
//    $("#" + textArea.id).resizable( "option", "alsoResize", '#' + note.id );
    html.appendChild(textArea);
    if(note.audio){
        var audio = document.createElement("audio");
        audio.setAttribute("src", note.audio);
        audio.setAttribute("controls", "controls");
        audio.innerHTML = "Your browser does not support the audio element";
        html.appendChild(audio);
    }
    if(note.video){
        var video = document.createElement("video");
        audio.setAttribute("src", note.video);
        audio.setAttribute("controls", "controls");
        audio.innerHTML = "Your browser does not support the video element";
        html.appendChild(video);
    }
    
    return html;
}

//return xml string of note
function generate_note_xml(note){
    var xml = "";
    xml += "<note>";
    xml += "<id>" + note.id + "</id>";
    xml += "<x_pos>" + note.x_pos + "</x_pos>";
    xml += "<y_pos>" + note.y_pos + "</y_pos>";
    xml += "<height>" + note.height + "</height>";
    xml += "<width>" + note.width + "</width>";
    xml += "<color>" + note.color + "</color>";
    xml += "<time>" + note.time + "</time>";
    xml += "<text>" + note.text + "</text>";
    if(note.audio){
        xml += "<audio>" + note.audio + "</audio>";
    }
    if(note.video){
        xml += "<video>" + note.video + "</video>";
    }
    xml += "</note>";
    return xml;
}

//return xml document of the notes
function parse_notes_to_xml(){
    var temp = "<notes>";
    for(var i = 0; i < notes.length; i++){
        temp += generate_note_xml(notes[i]);
    }
    temp += "</notes>";

    return parse_string_to_xml(temp);
}

//return xml document of the string
function parse_string_to_xml(string){
    if (window.DOMParser)
    {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(string,"text/xml");
    }
    else // Internet Explorer
    {
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(string);
    }
    //parse_notes_from_xml(xmlDoc);
    //alert(temp);
    return xmlDoc;
}

//return list of notes from xml
function parse_notes_from_xml(xml){
    var notes_xml = xml.getElementsByTagName("note");
    var temp_notes = new Array();
    for(var i = 0; i < notes_xml.length; i++){
        temp_notes[i] = new Object();
        temp_notes[i].id = notes_xml[i].getElementsByTagName("id")[0].textContent;
        temp_notes[i].x_pos = notes_xml[i].getElementsByTagName("x_pos")[0].textContent;
        temp_notes[i].y_pos = notes_xml[i].getElementsByTagName("y_pos")[0].textContent;
        temp_notes[i].height = notes_xml[i].getElementsByTagName("height")[0].textContent;
        temp_notes[i].width = notes_xml[i].getElementsByTagName("width")[0].textContent;
        temp_notes[i].color = notes_xml[i].getElementsByTagName("color")[0].textContent;
        temp_notes[i].text = notes_xml[i].getElementsByTagName("text")[0].textContent;
        temp_notes[i].time = notes_xml[i].getElementsByTagName("time")[0].textContent;
        if(notes_xml[i].getElementsByTagName("audio")){
            temp_notes[i].audio = notes_xml[i].getElementsByTagName("audio")[0].textContent;
        }
        if(notes_xml[i].getElementsByTagName("video")){
            temp_notes[i].video = notes_xml[i].getElementsByTagName("video")[0].textContent;
        }
    //TODO - Audio Video URLs
    }
    return temp_notes;
}

//return note object if found
function find_note(id){
    for(var i = 0; i < notes.length; i++){
        if(notes[i].id == id){
            return notes[i];
        }
    }
}

//return html target of the event
function target(e)
{
    var trgt;
    if (!e)
        var e = window.event;
    if (e.target)
        trgt = e.target;
    else if (e.srcElement)
        trgt = e.srcElement;
    if (trgt.nodeType == 3)
        trgt = trgt.parentNode;
    return trgt;
}

//return note object of html note element
function get_target_note(e){
    var targ = target(e);

    var reg_n = /noteboard/;
    var t_parent = targ.parentNode;

    if(t_parent.className == "note")
    {
        return find_note(t_parent.id);
    }
}

//saves the notes to the local storage
function unload(e){
    localStorage.notes = JSON.stringify(notes);
}

//
function click(e){

}

//
function mouse_down(e){
    cposx = e.clientX;
    cposy = e.clientY;
    var menu_note = document.getElementById("context_note");
    var menu_noteboard = document.getElementById("context_noteboard");
    var res = get_target_note(e);

    if(res){
        active_note = res;
        active_note.time = new Date().getTime();
        sort_notes();
        update_notes();
        noteboard.onmousemove = mouse_move;
        menu_note.style.visibility = "hidden";
        menu_noteboard.style.visibility = "hidden";
    }
    else{
        if(e.button != 2){
            var note = new_note(e.clientX - 50, e.clientY - 50, 100, 150, "rgba(210,240,0,0.8)", "");
            menu_note.style.visibility = "hidden";
            menu_noteboard.style.visibility = "hidden";
            notes_element.appendChild(parse_note_to_html(note));
            active_note = note;
            noteboard.onmousemove = mouse_move;
            update_notes();
        }
    }
}

//
function mouse_move(e){
    active_note.x_pos -= cposx - e.clientX;
    active_note.y_pos -= cposy - e.clientY;
    cposx = e.clientX;
    cposy = e.clientY;
    update_note_style(active_note);
}

//
function mouse_up(e){
    noteboard.onmousemove = null;
}

//
function context_menu(e){
    var trgt = get_target_note(e);
    if(trgt){
        var menu = document.getElementById("context_note");
        var o_menu = document.getElementById("context_noteboard");
        menu.style.visibility = "visible";
        o_menu.style.visibility = "hidden";
        menu.style.top = e.clientY + "px";
        menu.style.left = e.clientX + "px";
    }else{
        var menu = document.getElementById("context_noteboard");
        var o_menu = document.getElementById("context_note");
        o_menu.style.visibility = "hidden";
        menu.style.visibility = "visible";
        if(noteboard.clientHeight - e.clientY < menu.offsetHeight){
            menu.style.top = (e.clientY - menu.offsetHeight) + "px";
        }
        else{
            menu.style.top = e.clientY + "px";
        }
        if(noteboard.clientWidth - e.clientX < menu.offsetWidth){
            menu.style.left = (e.clientX - menu.offsetWidth) + "px";
        }
        else{
            menu.style.left = e.clientX + "px";
        }
    }
    return false;
}

//
function key_up(e){
    if(e.keyCode == 46)
    {
        var textarea = target(e);
        if(textarea)
        {
            if(textarea.value == "")
            {
                delete_note(find_note(textarea.parentNode.id));
            }
        }

    }else{
        text_area_change(e);
    }
    return true;
}

//updates the text of the note
function text_area_change(e){
    var text_area = target(e);
    var note = get_target_note(e);
    note.text = text_area.value;
    document.getElementById(note.id).getElementsByTagName("textarea")[0].value = note.text;
    send_changed_note_to_server(note);
}

function resize_text_area(event, ui){
    alert("RESIZE");
}

//send the notes to the server
function post_noteboard_to_server(){
    xmlhttp = get_XML_request_object();
    xmlhttp.onreadystatechange = ajax_ready_post_noteboard;
    xmlhttp.open("POST","/Noteboard/NoteboardServlet",true);
    xmlhttp.setRequestHeader("Content-type","text/xml");
    xmlhttp.send(parse_notes_to_xml());
}

//get notes from the server
function get_noteboard_from_server(_id)
{
    xmlhttp = get_XML_request_object();
    xmlhttp.onreadystatechange = ajax_ready_get_noteboard;
    xmlhttp.open("GET","/Noteboard/NoteboardServlet",true);
    xmlhttp.send(_id);
}

//response from server, post noteboard
function ajax_ready_post_noteboard()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        alert(xmlhttp.responseText);
    }
}

//response from server, get noteboard
function ajax_ready_get_noteboard()
{
    var noteboardXML;
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        noteboardXML = (new DOMParser()).parseFromString(xmlhttp.responseText, "text/xml");
        load_notes(parse_notes_from_xml(noteboardXML));
    }
}

//sends the changed note xml to the server
function send_changed_note_to_server(note){
//TODO
//    xmlhttp = get_XML_request_object();
//    xmlhttp.onreadystatechange = ajax_ready_send_changed_note;
//    xmlhttp.open("POST","/Noteboard/NoteboardChangeServlet",true);
//    xmlhttp.setRequestHeader("Content-type","text/xml");
//    xmlhttp.send(parse_string_to_xml(generate_note_xml(note)));
}

//response from server, send changed note
function ajax_ready_send_changed_note(){
//TODO
//    if (xmlhttp.readyState==4 && xmlhttp.status==200){
//
//    }
}

//return new xml request object
function get_XML_request_object()
{
    if (window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }
    else
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}